﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Diagnostics;

namespace OPENXMLLib
{
    public class ExernalLinkResolver
    {
        public static void Resolve(SpreadsheetDocument xDoc)
        {
            IList<Sheet> sheets = xDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().ToList();

            List<ExternalWorkbookPart> needDeleteExtWorkbook = new List<ExternalWorkbookPart>();

            foreach (var externalWorkbookPart in xDoc.WorkbookPart.ExternalWorkbookParts)
            {
                List<ExternalRelationship> ships = new List<ExternalRelationship>();

                foreach (var item in externalWorkbookPart.ExternalRelationships)
                {
                    ships.Add(item);
                }

                foreach (var ship in ships)
                {
                    bool needHold = false;
                    // 如果引用的即将生成的实例sheet，则不要删除
                    string relationShipUrl = ship.Uri.ToString();
                    foreach (var sheet in sheets)
                    {
                        if (sheet.Name == relationShipUrl)
                        {
                            needHold = true;
                            break;
                        }
                        else if (sheet.Name == "DT00." + relationShipUrl)
                        {
                            needHold = true;
                            break;
                        }
                    }

                    if (needHold)
                    {
                        Debug.WriteLine(string.Format("保留ExternalRelationship：({0}){1}", ship.Id, ship.Uri.ToString()));
                    }
                    else
                    {
                        Debug.WriteLine(string.Format("已处理ExternalRelationship：({0}){1}", ship.Id, ship.Uri.ToString()));
                        externalWorkbookPart.DeleteExternalRelationship(ship);
                        // 删除externalBook id=ship.id的

                        List<ExternalBook> ebooks = externalWorkbookPart.ExternalLink.Elements<ExternalBook>().ToList();
                        foreach (var ebook in ebooks)
                        {
                            if (ebook.Id == ship.Id)
                            {
                                Debug.WriteLine(string.Format("已处理ExternalBook：{0}", ebook.Id));
                                ebook.Remove();
                                break;
                            }
                        }
                        externalWorkbookPart.ExternalLink.Save();
                    }
                }

                if (externalWorkbookPart.ExternalLink.ChildElements.Count == 0)
                {
                    Debug.WriteLine(string.Format("已处理ExternalLink：{0}", externalWorkbookPart.ExternalLink.InnerText));
                    //List<ExternalLink> toBeDeleted = new List<ExternalLink>();
                    //toBeDeleted.Add(externalWorkbookPart.ExternalLink);
                    //externalWorkbookPart.DeleteParts<ExternalLink>(toBeDeleted);
                    needDeleteExtWorkbook.Add(externalWorkbookPart);
                }
            }
            xDoc.WorkbookPart.DeleteParts<ExternalWorkbookPart>(needDeleteExtWorkbook);
           
            if (xDoc.WorkbookPart.Workbook.ExternalReferences != null && xDoc.WorkbookPart.ExternalWorkbookParts.Count() == 0)
            {
                // workbook没有任何的扩展信息，那么久直接删除ExternalReferences节点
                xDoc.WorkbookPart.Workbook.ExternalReferences.Remove();
            }
            xDoc.WorkbookPart.Workbook.Save();
        }
    }
}
